package cz.proks.easyhelpdesk.gwt.activity;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import cz.proks.easyhelpdesk.api.model.User;
import cz.proks.easyhelpdesk.gwt.ClientFactory;
import cz.proks.easyhelpdesk.gwt.Globals;
import cz.proks.easyhelpdesk.gwt.activity.base.BaseActivity;
import cz.proks.easyhelpdesk.gwt.place.HelpdesksPlace;
import cz.proks.easyhelpdesk.gwt.place.WelcomePlace;
import cz.proks.easyhelpdesk.gwt.place.base.HelpdeskPlace;
import cz.proks.easyhelpdesk.gwt.restapi.RestDomainCallback;
import cz.proks.easyhelpdesk.gwt.restapi.UserRestApi;
import cz.proks.easyhelpdesk.gwt.ui.widget.LoadingWidget;
import cz.proks.easyhelpdesk.gwt.utils.CookieUtils;

public class DefaultActivity extends BaseActivity<HelpdeskPlace> {

    public DefaultActivity(Place place, ClientFactory clientFactory, PlaceHistoryMapper placeMapper) {
        super(null, clientFactory, placeMapper);
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        panel.setWidget(new LoadingWidget());
        
        Long cookieUserId = CookieUtils.getCookieUserId();

        if (cookieUserId == null || cookieUserId.equals(-1))
            switchByUser(null);

        else
            new UserRestApi().get(cookieUserId, new RestDomainCallback<User>() {
                @Override
                public void onDomainSuccess(User domain) {
                    switchByUser(domain);
                }
            });
    }

    private void switchByUser(User user) {
        Globals.setCurrentUser(user);
        CookieUtils.setCookieUser(user);

        if (user != null)
            redirectToHelpdesks();
        else
            redirectToWelcome();

    }

    private void redirectToWelcome() {
        getClientFactory().getPlaceController().goTo(new WelcomePlace());
    }

    private void redirectToHelpdesks() {
        getClientFactory().getPlaceController().goTo(new HelpdesksPlace());
    }
}
